package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zhentao.mapper.WmUserMapper;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.wemwdia.dto.WmLoginDto;
import com.zhentao.model.wemwdia.pojo.WmUser;
import com.zhentao.service.WmUserService;
import com.zhentao.utils.common.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl implements WmUserService {
    @Autowired
    private WmUserMapper wmUserMapper;
    @Override
    public ResponseResult login(WmLoginDto dto) {
        if(StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "帐号或密码为空");
        }
        WmUser wmUser = wmUserMapper.selectOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if(wmUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"帐号或密码错误");
        }
        String salt = wmUser.getSalt();
        String password = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        if(!password.equals(wmUser.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "账号或密码错误");
        }
        String token = AppJwtUtil.getToken(wmUser.getId().longValue());
        Map<String,Object> map=new HashMap<>();
        map.put("token", token);
        wmUser.setPassword(null);
        wmUser.setSalt(null);
        map.put("user", wmUser);
        return ResponseResult.okResult(map);
    }
}
